
global path "YOUR_PATH\Replication_Code"

use "$path\01_InData\ccm_data_quarterly.dta", clear

gen cusip_6 = substr(cstat_cusip, 1, 6)

gen pends_year  = year(datadate)
gen pends_month = month(datadate)

merge m:1 cusip_6 pends_year pends_month using "$path\01_InData\ibes_ea_dates.dta"
drop if _merge ==1
drop _merge

gen ea_date = .
replace ea_date = rdq     if !missing(rdq)  &  missing(anndats)
replace ea_date = anndats if  missing(rdq)  & !missing(anndats)
replace ea_date = rdq     if rdq <  anndats & !missing(rdq) & !missing(anndats)
replace ea_date = anndats if rdq >  anndats & !missing(rdq) & !missing(anndats)
replace ea_date = rdq     if rdq == anndats & !missing(rdq) & !missing(anndats)

drop rdq
gen rdq = ea_date

drop permno
gen permno = lpermno

sort gvkey rdq
bys gvkey: gen l1_rdq = rdq[_n - 1]
bys gvkey: gen l2_rdq = rdq[_n - 2]
bys gvkey: gen l3_rdq = rdq[_n - 3]
bys gvkey: gen l4_rdq = rdq[_n - 4]
bys gvkey: gen l5_rdq = rdq[_n - 5]
format l1_rdq l2_rdq l3_rdq l4_rdq l5_rdq %d

bys permno pends_year pends_month: gen dup=cond(_N==1,0,_n)
keep if dup<2
drop dup

save "$path\02_OutData\ccm_data_quarterly_to_merge.dta", replace